library(car)  ## We use version 2.0-25
library(plyr)  ## We use version 1.8.35
library(dplyr) ## We use version 0.4.2
library(foreign) ## We use version 0.8-65
library(ggplot2) ## We use version 1.0.1
library(lme4) ## We use version 1.1-8
library(mapproj) ## We use version 1.2-3
library(maps) ## We use version 2.3-10 
                                        #library(parallel) ## Base package in R
library(pbapply) ## We use version 1.1-1
library(pscl) ## We use version 1.4.9 
library(reshape2) ## We use version 1.4.1
library(rms) ## We use version 4.3-1
library(stringr)  ## 1.0.0
library(survey)  ## 3.30-3 
library(devtools)  ## 1.8.0
library(tidyr)

FileName <- function (path=NULL, name=NULL, ext=NULL, replace=FALSE) {
    p <- paste(path, collapse = "")
    n <- paste(name, collapse = "")
    e <- paste(".", ext, sep = "")
    d <- format(Sys.Date(), "%y%m%d") 
    for (l in seq_along(letters)) {
        if (l > 1) old_file_name <- file_name
        file_name <- paste0(p, d, paste(n, letters[l], sep="-"), e)
        if (!any(grepl(file_name, list.files()))) {
            if (replace) file_name <- ifelse(l > 1, old_file_name, file_name)
            break
        }
    }
    cat("\nFile name:", file_name, "\n\n")
    return(file_name)
}

mypdf <- function(name, ...) {
    date <- format(Sys.Date(), "%y%m%d")
    pdf(paste(paste(name, collapse=""), date, ".pdf", sep=""), ...)
}
mysw <- function (...) {
    setwd(paste(..., sep = "/"))
}
## Multiple plot function
multiplot <- function(..., plotlist = NULL, file, cols = 1, layout = NULL) {
    require(grid)
    ## Make a list from the ... arguments and plotlist
    plots <- c(list(...), plotlist)
    numPlots = length(plots)
    ## If layout is NULL, then use 'cols' to determine layout
    if (is.null(layout)) {
        ## Make the panel
        ## ncol: Number of columns of plots
        ## nrow: Number of rows needed, calculated from ## of cols
        layout <- matrix(seq(1, cols * ceiling(numPlots/cols)), 
                         ncol = cols, nrow = ceiling(numPlots/cols))
    }
    if (numPlots == 1) {
        print(plots[[1]])
    } else {
        ## Set up the page
        grid.newpage()
        pushViewport(viewport(layout = grid.layout(nrow(layout), ncol(layout))))

        ## Make each plot, in the correct location
        for (i in 1:numPlots) {
            ## Get i, j matrix positions of regions that contain this subplot
            matchidx <- as.data.frame(which(layout ==  i, arr.ind = TRUE))

            print(plots[[i]], vp = viewport(layout.pos.row = matchidx$row, 
                                            layout.pos.col = matchidx$col))
        }
    }
}





############
## Figure 1: Figure 1: Mass Support for Same-Sex Marriage in 2014
############


### PLOTS ###
theme_clean <- function (base_size = 12) { 
    require(grid) # Needed for unit() function
    theme_grey(base_size) %+replace%
        theme(
            axis.title = element_blank(), 
            axis.text = element_blank(), panel.background = element_blank(), 
            panel.grid = element_blank(), axis.ticks.length = unit(0, "cm"), 
            axis.ticks.margin = unit(0, "cm"), 
            panel.margin = unit(0, "lines"), 
            plot.margin = unit(c(0, 0, 0, 0), "lines"), complete = TRUE
        ) 
}


POtoCode <- function (pos, dta = st.info) {
    return(as.integer(dta$ICPSRCode[match(pos, dta$POAbrv)]))
}
CodeToName <- function (stcodes, dta = st.info) {
    return(as.character(dta$Name[match(stcodes, dta$ICPSRCode)]))
}
states <- read.csv(file = "states_icpsr.csv")

states$NAME <- gsub(" ", "", states$NAME)
states$NAME[states$NAME == "DistrictofColumbia"] <- "District of Columbia"
states$NAME[states$NAME == "NewHampshire"] <- "New Hampshire"
states$NAME[states$NAME == "NewJersey"] <- "New Jersey"
states$NAME[states$NAME == "NewMexico"] <- "New Mexico"
states$NAME[states$NAME == "NewYork"] <- "New York"
states$NAME[states$NAME == "NorthCarolina"] <- "North Carolina"
states$NAME[states$NAME == "NorthDakota"] <- "North Dakota"
states$NAME[states$NAME == "RhodeIsland"] <- "Rhode Island"
states$NAME[states$NAME == "SouthCarolina"] <- "South Carolina"
states$NAME[states$NAME == "SouthDakota"] <- "South Dakota"

states$NAME[states$NAME == "WestVirginia"] <- "West Virginia"

states <- states[, c(1, 2, 6)]
states$state <- tolower(states$NAME)

marriage_year <- 2012

ssm_scale <- read.csv(file = "gaymarriage_xs_psraking8k_dgirtout_2012.csv")

ssm.dta <- ssm_scale %>%
    filter(year == marriage_year & !is.na(year)) %>%
    mutate(StPO = gsub("abb", "", abb),
           stpo = tolower(abb)) 

liberalism.map <- map_data("state")
liberalism.map <- merge(liberalism.map, states, by.x = "region", by.y = "state")
liberalism.map <- merge(liberalism.map, ssm.dta,
                        by.x = "STATEAB", by.y = "StPO")
liberalism.map <- arrange(liberalism.map, group, order)

mypdf("Figures/map_gaymarriage", height = 3.5, width =7)
(p1 <- ggplot(data = liberalism.map, 
              aes(x = long, y = lat, group = group, fill = value_mean))
    + geom_polygon(colour = "black", size = rel(.1))
    + coord_map("polyconic")
    + scale_fill_gradient2(name = "", low = "red", mid = "white",
                           high = "blue", midpoint = .58)
    + theme_clean()
)
dev.off()

############
## Figure 2: Responsiveness on Same-Sex Marriage in 2014
############

AVA_GayMarriage<-read.csv(file="AVA_GayMarriage.csv")

AVA_GayMarriage <- subset(AVA_GayMarriage, Year == marriage_year + 1)
ssm.dta <- merge(ssm.dta, states, by.x = "StPO", by.y = "STATEAB")
ssm.dta <- merge(ssm.dta, AVA_GayMarriage, by.x = "NAME", by.y = "State")

binomial_smooth <- function(...) {
    geom_smooth(method = "glm", method.args = list(family = "binomial"), ...)
}
                                        # 
mypdf("Figures/xs_responsiveness_ssm", height = 3.5, width = 7)
ssm.dta %>%
    ggplot(aes(value_mean, legal, label = StPO)) +
    ylab(paste0("Same-Sex Marriage Policy (", marriage_year + 1, ")")) +
    xlab(paste0("Public Support for Same-Sex Marriage (", marriage_year, ")")) +
    binomial_smooth() +
    geom_text(size=2, position = position_jitter(height = .1)) +
    scale_y_continuous(breaks = c(0, 1), labels = c("Not Legal", "Legal"),
                       minor_breaks = c(0, 1)) +
    theme_bw()
dev.off()

